﻿#region License, Terms and Conditions
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
#endregion
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Pesta.DataAccess.Azure;
using raya.Library;

namespace raya
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
#if AZURE
        private ApplicationInitAzureTables azureInit;
        private AzureBlob blobInit;
#endif
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            // remove this route if you want to have a favicon for your site
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon(.*)?" });

            routes.MapRoute(
                "Messages",                                              // Route name
                "profile/messages/{cmd}/{msgid}",                           // URL with parameters
                new { controller = "profile", action = "messages", cmd = "", msgid = "" }  // Parameter defaults
            );

            routes.MapRoute(
                "Application",                                              // Route name
                "profile/application/{pid}/{aid}/{mid}",                           // URL with parameters
                new { controller = "profile", action = "Application", pid = "", aid = "", mid = "" }  // Parameter defaults
            );

            routes.MapRoute(
                "Edit Profile",                                              // Route name
                "profile/edit/{pid}/{aid}/{mid}",                           // URL with parameters
                new { controller = "profile", action = "Edit", pid = "", aid = "", mid = "" }  // Parameter defaults
            );

            routes.MapRoute(
                "Profile",                                              // Route name
                "profile/{id}",                           // URL with parameters
                new { controller = "profile", action = "Index", id = "" }  // Parameter defaults
            );

            routes.MapRoute(
                "Apps",                                              // Route name
                "apps/{action}/{aid}/{mid}",                           // URL with parameters
                new { controller = "apps", action = "Index", aid = "", mid = "" }  // Parameter defaults
            );

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{id}",                                    // URL with parameters
                new { controller = "Home", action = "Index", id = "" } , // Parameter defaults
                new { id = @"\d{1,}" }
            );

            routes.MapRoute(
                "Normal",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

            

            routes.MapRoute("Catch All", "{*path}", new { controller = "Error", action = "NotFound" });
        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);

            ViewEngines.Engines.Add(new RayaViewEngine());
        }
        protected void Application_BeginRequest()
        {
#if AZURE
            azureInit = ApplicationInitAzureTables.Init;
            blobInit = AzureBlob.Init;
#endif
            // An "Accept : application/xrds+xml" header means they want our XRDS document (and nothing else) 
            if (!String.IsNullOrEmpty(Context.Request.Params["HTTP_ACCEPT"]) && 
                Context.Request.Params["HTTP_ACCEPT"] == "application/xrds+xml" &&
                Context.Request.Path == "/xrds")
            {
                Response.ContentType = "application/xrds+xml";
                //Response.ContentType = "text/xml"; // turn this on and comment out the previous line to view it easily in a browser
                Response.Write(XRDS.getXRDS(RayaSettings.Gadget_server, "http://" + Context.Request.Params["HTTP_HOST"]));
                Response.End();
            }

            // for SWFUpload
            try
            {
                const string session_param_name = "ASPSESSID";
                const string session_cookie_name = "ASP.NET_SESSIONID";

                if (HttpContext.Current.Request.Form[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
                }
            }
            catch (Exception)
            {
                Response.StatusCode = 500;
                Response.Write("Error Initializing Session");
            }

            // uncomment the following if IIS does not find Default.aspx
            //if (Context.Request.FilePath.Equals("/"))
            //    Context.RewritePath("Default.aspx");

        }

        protected static void UpdateCookie(string cookie_name, string cookie_value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
            if (cookie == null)
            {
                cookie = new HttpCookie(cookie_name);
                HttpContext.Current.Request.Cookies.Add(cookie);
            }
            cookie.Value = cookie_value;
            HttpContext.Current.Request.Cookies.Set(cookie);
        }
    }
}